package com.smxy.daydayup.service.serviceImpl;

import com.smxy.daydayup.mapper.SectionTreeMapper;
import com.smxy.daydayup.pojo.SectionTree;
import com.smxy.daydayup.pojo.dto.TreeNode;
import com.smxy.daydayup.service.SectionTreeService;
import com.smxy.daydayup.util.tree.TreeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @team daydayup
 * @time 2021-12-12 8:29
 */
@Service
public class SectionTreeServiceImpl implements SectionTreeService {

    @Resource
    private SectionTreeMapper sectionTreeMapper;

    @Override
    public int deleteByPrimaryKey(Long sectionId) {
        return sectionTreeMapper.deleteByPrimaryKey(sectionId);
    }

    @Override
    public int insert(SectionTree record) {
        return sectionTreeMapper.insert(record);
    }

    @Override
    public int insertSelective(SectionTree record) {
        return sectionTreeMapper.insertSelective(record);
    }

    @Override
    public SectionTree selectByPrimaryKey(Long sectionId) {
        return sectionTreeMapper.selectByPrimaryKey(sectionId);
    }

    @Override
    public int updateByPrimaryKeySelective(SectionTree record) {
        return sectionTreeMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(SectionTree record) {
        return sectionTreeMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<SectionTree> getTreeList(Integer courseId) {
        List<SectionTree> all = sectionTreeMapper.selectListByCourseId(courseId);
        return TreeUtils.getTreeList(all);
    }

    @Override
    @Transactional
    public int updateTree(List<SectionTree> treeList,Integer courseId) {
        Integer record = courseId;
        sectionTreeMapper.deleteTreeByCourseId(record);
        if(sectionTreeMapper.selectListByCourseId(record).size()<1){
            for (SectionTree sectionTree : treeList) {
                sectionTree.setCourseId(record);
                sectionTreeMapper.insertSelective(sectionTree);
            }
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public void addNode(TreeNode treeNode, Integer courseId) {
        sectionTreeMapper.insertSelective(SectionTree.builder()
                        .label(treeNode.getNodeName())
                        .id(sectionTreeMapper.selectNextNodeIdOfCourse(courseId))
                        .courseId(courseId)
                .build());
    }

}

